/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.yanlight.Constants;
import com.yanlight.app.request.WxAuthCallbackRequest;
import com.yanlight.app.request.WxCertRequest;
import com.yanlight.app.response.WxCertResponse;
import com.yanlight.app.service.WxMsgReceiverService;
import com.yanlight.exception.ErrorType;
import com.yanlight.support.http.Response;
import com.yanlight.support.wx.WxConstants;
import com.yanlight.support.wx.model.WxCertSign;
import com.yanlight.support.wx.model.WxSnsOauth;
import com.yanlight.support.wx.util.SignatureUtil;
import com.yanlight.support.wx.util.WxUtil;
import com.yanlight.util.CookieUtil;
import com.yanlight.util.EncryptUtil;
import com.yanlight.util.RandomStringUtil;
import com.yanlight.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.SortedMap;

/**
 * @author haolw
 * @time 2017/07/20
 */
@Controller
@RequestMapping("/wx")
public class WxController extends BaseController {

    @Autowired
    WxMsgReceiverService wxMsgReceiverService;


    /**
     * 微信h5 管理员登录
     *
     * @param request
     * @return
     */
    @RequestMapping("/wxManagerLogin")
    @ResponseBody
    public Response wxManagerLogin(HttpServletRequest request) {

        String userAuthId = CookieUtil.getValue(request, Constants.WX_OPENID);
        if (StringUtils.isBlank(userAuthId)) {
            return ResponseUtil.fail(ErrorType.AUTH_FAIL);
        }

        boolean isExist = wxMsgReceiverService.checkPermission(userAuthId);
        if (!isExist) {
            return ResponseUtil.fail(ErrorType.NO_AUTH);
        }

        return ResponseUtil.success();
    }


    @RequestMapping("/getOpenId")
    public String getOpenId(WxAuthCallbackRequest request) {
        String code = request.getCode();
        if (StringUtils.isBlank(code)) {
            return Constants.NO_SERVICE_VIEW;
        }
        String redirectUrl = EncryptUtil.decodeBase64(request.getUrl());
        try {
            String appId = WxConstants.appId;
            String appSecret = WxConstants.appSecret;
            WxSnsOauth snsOauth = WxUtil.getOpenId(appId, appSecret, code);
            if (snsOauth != null) {
                String openid = snsOauth.getOpenid();
                CookieUtil.addCookie(Constants.WX_OPENID, openid);
                return redirect(redirectUrl);
            } else {
                return Constants.NO_SERVICE_VIEW;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Constants.NO_SERVICE_VIEW;
        }
    }

    @RequestMapping("/getCert")
    @ResponseBody
    public String getCert(WxAuthCallbackRequest request) {
        WxCertSign certSign = new WxCertSign();
        String nonceStr = RandomStringUtil.randomAlphanumeric(32);
        certSign.setNonce_str(nonceStr);
        certSign.setMch_id(WxConstants.mchId);
        SortedMap<String, String> stringStringSortedMap = certSign.signParams();
        String apiSign = SignatureUtil.createApiSignHMAC(stringStringSortedMap, WxConstants.apiKey);
        certSign.setSign(apiSign);

        SortedMap<String, String> paramsMap = certSign.getParamsMap();

        WxCertRequest wxRequest = new WxCertRequest(paramsMap);
        WxCertResponse execute = wxRequest.execute();

        return JSONObject.toJSONString(execute);
    }

}
